<script setup>
import PlusIcon from '@/components/icons/PlusIcon.vue'
import { ref } from 'vue'
import { upload } from '@/service/file.js'
async function handleFileSelect(event) {
  const selectedFile = event.target.files[0]
  const res = await upload(selectedFile)
  emit('update:modelValue', res.data)
}
const fileInput = ref()
function openFileSelector() {
  fileInput.value.click()
}
// 声明接收父组件v-model的值，默认名为modelValue
defineProps({
  modelValue: {
    type: String, // 根据实际图片地址类型定义，也可支持Array等
    default: '',
  },
})
const emit = defineEmits(['update:modelValue'])
</script>

<template>
  <div :class="{ 'no-border': modelValue }" class="upload-image" @click="openFileSelector">
    <img v-if="modelValue" :src="modelValue" alt="上传的图片" style="width: 100%; height: 100%" />
    <el-icon v-else size="35">
      <PlusIcon />
    </el-icon>
    <input
      ref="fileInput"
      accept="image/*"
      class="hidden-file-input"
      style="display: none"
      type="file"
      @change="handleFileSelect"
    />
  </div>
</template>

<style lang="scss" scoped>
.upload-image {
  width: 100px;
  height: 100px;
  border: 1px dashed gray;
  color: gray;
  display: flex;
  justify-content: center;
  align-items: center;
  &:hover {
    border: 1px dashed #409eff;
    color: #409eff;
    cursor: pointer;
  }

  &.no-border {
    border: none;
    &:hover {
      border: none;
    }
  }
}
</style>
